param ( [string] $ConfigFile=$DefaultDatabaseConfigFile
      , [string] $EnvironmentName=$DefaultDatabaseEnv
			, [string] $ServerName=$DefaultServerName
			, [string] $DatabaseName=$DefaultDatabaseName
			, [string] $Username=$DefaultUsername
			, [string] $Password=$DefaultPassword
      , [switch] $Whatif
			, [switch] $Force
			)

. Resolve-DbDeploymentParms 

#region Queries
	$TestDatabaseQuery = "SELECT count(*) FROM sys.databases WHERE name='{0}'"

	$DropDatabaseQuery = @"
USE [master]
GO
IF EXISTS(select name from sys.databases where name='{0}')
BEGIN
	EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'{0}'
	ALTER DATABASE [{0}] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
	DROP DATABASE [{0}]
END
"@
#endregion

$PSSqlConnection = $PSSqlConnectionClass.New($ServerName,"master",$Username,$Password)
try {

	$PSSqlCommand = $PSSqlCommandClass.New($PSSqlConnection)
	
	$PSSqlCommand.Command.CommandType = [System.Data.CommandType]::Text
	$PSSqlCommand.Command.CommandText = $TestDatabaseQuery -f $DatabaseName
	
	$CatalogExits =  ($PSSqlCommand.Command.ExecuteScalar() -ne 0)
	
	if ($CatalogExits -and (-not $force))
	{
		$response = Read-Host "Are you sure you want to drop the existing Catalog '$DatabaseName' on server '$ServerName'? [Y/N]"
		if ($response -ne 'y')
		{
			Throw "Database $DatabaseName not dropped"
		}
	}
	
	Log-Warning "Dropping Database $DatabaseName"
	
	$PSSqlCommand.ExecuteNonQuery($DropDatabaseQuery -f $DatabaseName)

	$PSSqlConnection.Connection.Close()
} -finally {
	$PSSqlConnection.Connection.Dispose()
	$PSSqlConnection.Connection = $null
	$PSSqlConnection = $null
}
